package controller

import (
	"fmt"
	"log"
	"user-center/entity"
	"user-center/vo"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sgin"
	"github.com/androidsr/sc-go/sgorm"
	"github.com/androidsr/sc-go/sjwt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
)

const (
	SUCCESS    = 200
	AUTHORIZED = "Authorized"
	USER       = "userId"
	NAME       = "userName"
	ROLE       = "roleId"
)

func init() {
	sgin.AddRouter(LoginController{})
}

type LoginController struct {
}

// 用户登录
// @Router [post] [/doLogin]
func (LoginController) DoLogin(c *gin.Context) any {
	user := struct {
		DeviceCode    string `json:"deviceCode"`
		LoginType     int    `json:"loginType"`
		LoginId       string `json:"loginId"`
		LoginPassword string `json:"loginPassword"`
	}{}
	c.BindJSON(&user)
	if user.LoginId == "" || user.LoginPassword == "" {
		return model.NewFail(1001, "用户名或密码不能为空！")
	}
	data := new(entity.SysUsers)
	data.UserId = user.LoginId
	err := sgorm.DB.GetOne(data)
	fmt.Println(err)
	if err != nil {
		return model.NewFail(1001, "获取用户信息失败")
	}
	if data.LoginPassword == "" || data.LoginPassword != user.LoginPassword {
		return model.NewFail(1001, "账号或密码不正确！")
	}
	claims := jwt.MapClaims{}
	claims[USER] = data.UserId
	claims[NAME] = data.UserName
	//claims[ROLE] = data.roleId

	tokenStr, err := sjwt.GenerateToken(claims)
	if err != nil {
		log.Print(err)
		return model.NewFail(1001, "创建认证信息失败")
	}
	sjwt.SetWebToken(c, tokenStr)
	result := &vo.LoginResultVO{HttpResult: model.HttpResult{Code: 200, Msg: "登录成功"},
		Token: tokenStr, UserId: data.UserId, UserName: data.UserName}
	return result
}

// 修改密码
// @Router [put] [/repasswd]
func (LoginController) ResetPasswd(c *gin.Context) any {
	info := struct {
		UserId    string `json:"userId"`
		NewPasswd string `json:"newPasswd"`
		Passwd    string `json:"passwd"`
	}{}
	c.ShouldBind(&info)
	if info.UserId == "" || info.Passwd == "" || info.NewPasswd == "" {
		return model.NewFail(1001, "输入信息不完整")
	}
	data := new(entity.SysUsers)
	data.UserId = info.UserId
	err := sgorm.DB.SelectOne(data, data)
	if err != nil {
		return model.NewFail(1001, "获取用户信息失败")
	}

	if data.LoginPassword != info.Passwd {
		return model.NewFail(1001, "账号或密码不正确！")
	}
	data.LoginPassword = info.NewPasswd
	sgorm.DB.UpdateById(data)
	return model.NewOK(nil)
}

// 退出登录
func (LoginController) Logout(c *gin.Context) any {
	return model.NewOK(nil)
}
